﻿using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;

namespace CommonUtils
{
    public static partial class HttpExtension
    {
        #region WebRequest WebResponse
        /// <summary>
        /// WebRequest添加文本
        /// </summary>
        public static void AddText(this WebRequest request, string text, Encoding encoding = null)
        {
            var requestStream = request.GetRequestStream();
            var writer = new StreamWriter(requestStream, encoding.Null2utf8());
            writer.Write(text);
            writer.Close();
            requestStream.Close();
        }

        /// <summary>
        /// WebRequest添加内存流
        /// </summary>
        public static void AddStream(this WebRequest request, Stream stream)
        {
            var requestStream = request.GetRequestStream();
            stream.CopyTo(requestStream);
            stream.Close();
            requestStream.Close();
        }

        /// <summary>
        /// WebRequest添加二进制
        /// </summary>
        public static void AddBytes(this WebRequest request, byte[] bytes)
        {
            var requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, bytes.Length);
            requestStream.Close();
        }

        /// <summary>
        /// WebRequest添加文件
        /// </summary>
        public static void AddFile(this WebRequest request, string path)
        {
            var requestStream = request.GetRequestStream();
            var fileStream = File.OpenRead(path);
            fileStream.CopyTo(requestStream);
            fileStream.Close();
            requestStream.Close();
        }

        /// <summary>
        /// WebResponse获取文本
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static string GetText(this WebResponse response, Encoding encoding = null)
        {
            var stream = response.GetResponseStream();
            var reader = new StreamReader(stream, encoding.Null2utf8());
            var res = reader.ReadToEnd();
            reader.Close();
            stream.Close();
            return res;
        }

        /// <summary>
        /// WebResponse获取文件
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public static void SaveFile(this WebResponse response, string path)
        {
            var stream = response.GetResponseStream();
            var fileStream = File.Create(path);
            stream.CopyTo(fileStream);
            fileStream.Close();
            stream.Close();
        }
        #endregion

        #region HttpResponseMessage
        public static string ReadString(this HttpResponseMessage message)
        {
            try
            {
                if (message.StatusCode != HttpStatusCode.OK)
                    return default;
                return message.Content.ReadAsStringAsync().Result;
            }
            catch (Exception ex)
            {
                LogUtil.PrintInfo("HttpResponseMessage ReadString Error: " + ex.Message);
                return default;
            }
        }
        public static string GetString(this HttpResponseMessage message)
        => message.ReadString();

        public static Stream ReadStream(this HttpResponseMessage message)
        {
            try
            {
                if (message.StatusCode != HttpStatusCode.OK)
                    return default;
                return message.Content.ReadAsStreamAsync().Result;
            }
            catch (Exception ex)
            {
                LogUtil.PrintInfo("HttpResponseMessage ReadStream Error: " + ex.Message);
                return default;
            }
        }
        public static Stream GetStream(this HttpResponseMessage message)
        => message.ReadStream();

        public static byte[] ReadBytes(this HttpResponseMessage message)
        {
            try
            {
                if (message.StatusCode != HttpStatusCode.OK)
                    return default;
                return message.Content.ReadAsByteArrayAsync().Result;
            }
            catch (Exception ex)
            {
                LogUtil.PrintInfo("HttpResponseMessage ReadBytes Error: " + ex.Message);
                return default;
            }
        }
        public static byte[] GetBytes(this HttpResponseMessage message)
        => message.ReadBytes();

        public static JToken ReadJToken(this HttpResponseMessage message)
        {
            try
            {
                if (message.StatusCode != HttpStatusCode.OK)
                    return default;
                return message.Content.ReadAsStringAsync().Result.ParseToJToken();
            }
            catch (Exception ex)
            {
                LogUtil.PrintInfo("HttpResponseMessage ReadJToken Error: " + ex.Message);
                return default;
            }
        }
        public static JToken GetJToken(this HttpResponseMessage message)
        => message.ReadJToken();

        public static JObject ReadJObject(this HttpResponseMessage message)
        {
            try
            {
                if (message.StatusCode != HttpStatusCode.OK)
                    //因为framework不支持ApiResult，所以这里直接用json结构
                    return new JObject {
                        { "Code", (int)message.StatusCode },
                        { "Message", message.StatusCode.ToString() },
                        { "Data", message.ReasonPhrase }
                    };
                return message.Content.ReadAsStringAsync().Result.ParseToJObject();
            }
            catch (Exception ex)
            {
                LogUtil.PrintInfo("HttpResponseMessage ReadJObject Error: " + ex.Message);
                return default;
            }
        }
        public static JObject GetJObject(this HttpResponseMessage message)
        => message.ReadJObject();

        public static JArray ReadJArray(this HttpResponseMessage message)
        {
            try
            {
                if (message.StatusCode != HttpStatusCode.OK)
                    return default;
                return message.Content.ReadAsStringAsync().Result.ParseToJArray();
            }
            catch (Exception ex)
            {
                LogUtil.PrintInfo("HttpResponseMessage ReadJArray Error: " + ex.Message);
                return default;
            }
        }
        public static JArray GetJArray(this HttpResponseMessage message)
        => message.ReadJArray();
        #endregion
    }
}
